package com.cyzy.homework.controller;

import com.cyzy.homework.common.Result;
import com.cyzy.homework.dto.HomeworkDTO;
import com.cyzy.homework.service.HomeworkService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.web.bind.annotation.*;

import jakarta.validation.Valid;
import java.util.List;

/**
 * 作业控制器
 */
@RestController
@RequestMapping("/api/homework")
@CrossOrigin(origins = "*")
public class HomeworkController {
    
    @Autowired
    private HomeworkService homeworkService;
    
    /**
     * 创建作业
     */
    @PostMapping
    public Result<HomeworkDTO> createHomework(@Valid @RequestBody HomeworkDTO homeworkDTO) {
        try {
            HomeworkDTO result = homeworkService.createHomework(homeworkDTO);
            return Result.success("作业创建成功", result);
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }
    
    /**
     * 更新作业
     */
    @PutMapping("/{id}")
    public Result<HomeworkDTO> updateHomework(@PathVariable Long id, 
                                            @Valid @RequestBody HomeworkDTO homeworkDTO) {
        try {
            HomeworkDTO result = homeworkService.updateHomework(id, homeworkDTO);
            return Result.success("作业更新成功", result);
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }
    
    /**
     * 删除作业
     */
    @DeleteMapping("/{id}")
    public Result<Void> deleteHomework(@PathVariable Long id, 
                                     @RequestParam String teacherId) {
        try {
            homeworkService.deleteHomework(id, teacherId);
            return Result.success();
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }
    
    /**
     * 获取所有作业列表（分页）
     */
    @GetMapping("/list")
    public Result<Page<HomeworkDTO>> getAllHomeworks(
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size,
            @RequestParam(defaultValue = "createTime") String sortBy,
            @RequestParam(defaultValue = "desc") String sortDir,
            @RequestParam(required = false) String classId,
            @RequestParam(required = false) String teacherId) {
        try {
            Sort sort = sortDir.equalsIgnoreCase("desc") ? 
                Sort.by(sortBy).descending() : Sort.by(sortBy).ascending();
            Pageable pageable = PageRequest.of(page, size, sort);
            
            Page<HomeworkDTO> result;
            if (classId != null && !classId.isEmpty()) {
                result = homeworkService.getHomeworksByClassId(classId, pageable);
            } else if (teacherId != null && !teacherId.isEmpty()) {
                result = homeworkService.getHomeworksByTeacherId(teacherId, pageable);
            } else {
                // 获取所有作业，需要在service中实现这个方法
                result = homeworkService.getAllHomeworks(pageable);
            }
            return Result.success(result);
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }

    /**
     * 根据ID查询作业
     */
    @GetMapping("/{id}")
    public Result<HomeworkDTO> getHomeworkById(@PathVariable Long id) {
        try {
            HomeworkDTO result = homeworkService.getHomeworkById(id);
            return Result.success(result);
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }
    
    /**
     * 根据班级ID查询作业列表
     */
    @GetMapping("/class/{classId}")
    public Result<Page<HomeworkDTO>> getHomeworksByClassId(
            @PathVariable String classId,
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size,
            @RequestParam(defaultValue = "createTime") String sortBy,
            @RequestParam(defaultValue = "desc") String sortDir) {
        try {
            Sort sort = sortDir.equalsIgnoreCase("desc") ? 
                Sort.by(sortBy).descending() : Sort.by(sortBy).ascending();
            Pageable pageable = PageRequest.of(page, size, sort);
            
            Page<HomeworkDTO> result = homeworkService.getHomeworksByClassId(classId, pageable);
            return Result.success(result);
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }
    
    /**
     * 根据教师ID查询作业列表
     */
    @GetMapping("/teacher/{teacherId}")
    public Result<Page<HomeworkDTO>> getHomeworksByTeacherId(
            @PathVariable String teacherId,
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size,
            @RequestParam(defaultValue = "createTime") String sortBy,
            @RequestParam(defaultValue = "desc") String sortDir) {
        try {
            Sort sort = sortDir.equalsIgnoreCase("desc") ? 
                Sort.by(sortBy).descending() : Sort.by(sortBy).ascending();
            Pageable pageable = PageRequest.of(page, size, sort);
            
            Page<HomeworkDTO> result = homeworkService.getHomeworksByTeacherId(teacherId, pageable);
            return Result.success(result);
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }
    
    /**
     * 根据班级ID和状态查询作业列表
     */
    @GetMapping("/class/{classId}/status/{status}")
    public Result<Page<HomeworkDTO>> getHomeworksByClassIdAndStatus(
            @PathVariable String classId,
            @PathVariable Integer status,
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size,
            @RequestParam(defaultValue = "createTime") String sortBy,
            @RequestParam(defaultValue = "desc") String sortDir) {
        try {
            Sort sort = sortDir.equalsIgnoreCase("desc") ? 
                Sort.by(sortBy).descending() : Sort.by(sortBy).ascending();
            Pageable pageable = PageRequest.of(page, size, sort);
            
            Page<HomeworkDTO> result = homeworkService.getHomeworksByClassIdAndStatus(classId, status, pageable);
            return Result.success(result);
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }
    
    /**
     * 根据教师ID和状态查询作业列表
     */
    @GetMapping("/teacher/{teacherId}/status/{status}")
    public Result<Page<HomeworkDTO>> getHomeworksByTeacherIdAndStatus(
            @PathVariable String teacherId,
            @PathVariable Integer status,
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size,
            @RequestParam(defaultValue = "createTime") String sortBy,
            @RequestParam(defaultValue = "desc") String sortDir) {
        try {
            Sort sort = sortDir.equalsIgnoreCase("desc") ? 
                Sort.by(sortBy).descending() : Sort.by(sortBy).ascending();
            Pageable pageable = PageRequest.of(page, size, sort);
            
            Page<HomeworkDTO> result = homeworkService.getHomeworksByTeacherIdAndStatus(teacherId, status, pageable);
            return Result.success(result);
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }
    
    /**
     * 发布作业
     */
    @PostMapping("/{id}/publish")
    public Result<HomeworkDTO> publishHomework(@PathVariable Long id, 
                                             @RequestParam String teacherId) {
        try {
            HomeworkDTO result = homeworkService.publishHomework(id, teacherId);
            return Result.success("作业发布成功", result);
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }
    
    /**
     * 结束作业
     */
    @PostMapping("/{id}/end")
    public Result<HomeworkDTO> endHomework(@PathVariable Long id, 
                                         @RequestParam String teacherId) {
        try {
            HomeworkDTO result = homeworkService.endHomework(id, teacherId);
            return Result.success("作业结束成功", result);
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }
    
    /**
     * 查询即将到期的作业
     */
    @GetMapping("/class/{classId}/upcoming")
    public Result<List<HomeworkDTO>> getUpcomingDeadline(
            @PathVariable String classId,
            @RequestParam(defaultValue = "7") int days) {
        try {
            List<HomeworkDTO> result = homeworkService.getUpcomingDeadline(classId, days);
            return Result.success(result);
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }
    
    /**
     * 查询已过期的作业
     */
    @GetMapping("/class/{classId}/expired")
    public Result<List<HomeworkDTO>> getExpiredHomeworks(@PathVariable String classId) {
        try {
            List<HomeworkDTO> result = homeworkService.getExpiredHomeworks(classId);
            return Result.success(result);
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }
    
    /**
     * 获取作业统计信息
     */
    @GetMapping("/{id}/statistics")
    public Result<HomeworkDTO> getHomeworkStatistics(@PathVariable Long id) {
        try {
            HomeworkDTO result = homeworkService.getHomeworkStatistics(id);
            return Result.success(result);
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }
}
